import { DownloadOutlined } from '@ant-design/icons';
import ProCard, { ProCardProps } from '@ant-design/pro-card';
import { save } from '@tauri-apps/api/dialog';
import { fs } from '@tauri-apps/api';
import { Button, Empty, message } from 'antd';
import React from 'react';
import Title from './Title';

type LoggingProps = {
  dataSource: string[];
  title?: string | React.ReactNode;
} & ProCardProps;

function Logging({ dataSource, title, loading, ...rest }: LoggingProps) {
  console.log('dataSource:', dataSource);
  return (
    <ProCard
      title={title ?? <Title level={3}>日志</Title>}
      size="small"
      headerBordered
      bordered
      loading={loading && dataSource.length === 0}
      extra={
        <Button
          icon={<DownloadOutlined />}
          type="link"
          size="small"
          disabled={dataSource.length == 0}
          onClick={async () => {
            const filepath = await save({
              // defaultPath: '',
              filters: [
                {
                  name: '日志文件',
                  extensions: ['log'],
                },
              ],
            });
            console.log(filepath);
            if (filepath) {
              try {
                await fs.writeFile({
                  path: filepath,
                  contents: dataSource.join('\n'),
                });
                message.info('保存成功！');
              } catch (error) {
                console.log(error);
                message.info(`保存失败：${error}`);
              }
            }
          }}
        />
      }
      {...rest}
    >
      {dataSource?.length > 0 ? null : <Empty />}
      <pre
        className="logging"
        style={{ maxHeight: 'calc(100vh - 160px)', overflow: 'auto' }}
      >
        {dataSource.map((line: string, i: number) => (
          <code key={i}>{line}</code>
        ))}
      </pre>
    </ProCard>
  );
}

export default Logging;
